package com.malethan.seemorej.taglib;

import com.malethan.seemorej.taglib.elements.Textfield;

/**
 * <p>Copyright &copy; 2009 Elwyn Malethan</p>
 * <p>TODO: A description of this file</p>
 */
public class TextAutocompleterTag extends ElementTag {
    //----------------------------------------------------------------------- Static Properties and Constants
    //----------------------------------------------------------------------- Static Methods
    //----------------------------------------------------------------------- Instance Properties

    String size;
    String maxlength;
    private String tokens;
    private String updateUrl;
    private String paramName;

    //----------------------------------------------------------------------- Constructors
    //----------------------------------------------------------------------- Getters and Setters

    public void setSize(String size) {
        this.size = size;
    }

    public void setMaxlength(String maxlength) {
        this.maxlength = maxlength;
    }

    public void setTokens(String tokens) {
        this.tokens = tokens;
    }

    public void setUpdateUrl(String updateUrl) {
        this.updateUrl = updateUrl;
    }

    public void setParamName(String paramName) {
        this.paramName = paramName;
    }

//----------------------------------------------------------------------- Instance Methods

    protected String constructElement() {
        Textfield textfield = new Textfield();

        setCommonAttributes(textfield);

        textfield.setSize(size);
        textfield.setMaxlength(maxlength);
        textfield.setAutocomplete("off");

        String javascript = constructJavaScript(textfield);

        StringBuilder html = new StringBuilder();
        html.append(textfield.toString());
        html.append(String.format("<div class=\"sj_autcompleter\" id=\"%sDiv\"></div>", htmlId));
        html.append(javascript);
        return html.toString();
    }

    private String constructJavaScript(Textfield textfield) {
        return String.format("" +
                "<script type=\"text/javascript\">\n" +
                "    new Ajax.Autocompleter(\n" +
                "        '%s',\n" +
                "        '%sDiv',\n" +
                "        '%s',\n" +
                "        {\n" +
                "            tokens: %s,\n" +
                "            paramName: '%s'\n" +
                "        }\n" +
                "    );\n" +
                "</script>", htmlId, htmlId, updateUrl, tokens, paramName);
    }

    public void release() {
        super.release();
        this.size = null;
        this.maxlength = null;
        this.tokens = null;
    }
}
